import { IPageResponse } from "../../types/CommonType";
import { ValidationError } from "../../utils/errors";
import { getTreeStructure } from "../../utils/tools";
import MessageTypeModel from "../../dao/model/HomePage/MessageTypeModel";
import MessageTypeEntity, { IMessageTypeModel } from "../../entities/HomePage/MessageTypeEntity";


export class MessageTypeService {
  /**
   * 添加数据
   */
  public static async add(admin: MessageTypeEntity): Promise<true> {
    // 1. 转换类型
    admin = MessageTypeEntity.transform(admin);
    // 2. 数据验证
    const errors = await admin.validateThis();
    if (errors.length > 0) {
      throw new ValidationError(errors[0]);
    }

    await MessageTypeModel.create<IMessageTypeModel>(admin);
    return true;
  }

  /**
   * 分页获取数据
   */
  public static async findByPage(offset: number, limit: number, where?): Promise<IPageResponse> {
    let data = await MessageTypeModel.findAndCountAll<IMessageTypeModel>({
      offset: limit * (offset - 1),
      limit,
      where,
    });

    const result: IPageResponse = {
      total: data.count,
      list: data.rows.map((item) => item.dataValues),
    };

    return result;
  }

  public static async findByList(where = {}) {
    return MessageTypeModel.findAll<IMessageTypeModel>({ where });
  }

  public static async findByTreeList(where: any = {}) {
    const result = await MessageTypeModel.findAll<IMessageTypeModel>({ where });

    return getTreeStructure<MessageTypeEntity>(result.map((item) => item.dataValues));
  }

  /**
   * 通过id获取数据
   */
  public static async findById(id: string) {
    return MessageTypeModel.findByPk<IMessageTypeModel>(id);
  }

  /**
   * 修改数据
   */
  public static async update(data: any) {
    return MessageTypeModel.update<IMessageTypeModel>(data, {
      where: {
        id: data.id,
      },
    });
  }

  /**
   * 删除数据
   */
  public static async delete(id: string) {
    return MessageTypeModel.destroy({
      where: {
        id,
      },
    });
  }
}